//self.moveTo(0,0);
//self.resizeTo(screen.availWidth,screen.availHeight);
import $ from 'jquery';

var signs = {
  onm: 0, //鼠标按键状态 0是无按键，1是鼠标右键
  x: 0,
  y: 0,
  pagewrite: '', //签名内容
  ones: 1, //起笔状态
  ispad: 0, //0为pc机，1为pad
  lineWidth: 20,
  beforePage: 0,
  beforePageName: 'page',

  CanvasDrawr: function(options) {
    console.log(options, '画布内容');
    xx = ''; //先清空签名
    // grab canvas element
    var canvas = document.getElementById(options.id),
      ctxt = canvas.getContext('2d');
    // set props from options, but the defaults are for the cool kids
    ctxt.lineWidth = options.size || Math.ceil(Math.random() * 35);
    ctxt.lineCap = options.lineCap || 'round';
    ctxt.pX = undefined;
    ctxt.pY = undefined;
    var lines = [];
    var offset = $(canvas).offset();

    var self = {
      //bind click events
      init: function() {
        //set pX and pY from first click
        canvas.addEventListener('touchstart', self.preDraw, false);
        canvas.addEventListener('touchmove', self.draw, false);
      },

      preDraw: function(event) {
        $.each(event.touches, function(i, touch) {
          var id = touch.identifier,
            colors = ['black', 'green', 'yellow', 'blue', 'magenta', 'orangered'],
            mycolor = colors[0];
          lines[id] = { x: this.pageX - offset.left, y: this.pageY - offset.top, color: mycolor };
        });
        if (xx != '') {
          xx += ')(';
        }

        event.preventDefault();
      },

      draw: function(event) {
        var e = event,
          hmm = {};

        $.each(event.touches, function(i, touch) {
          var id = touch.identifier,
            moveX = this.pageX - offset.left - lines[id].x,
            moveY = this.pageY - offset.top - lines[id].y;
          this.ispad = 1;
          var ret = self.move(id, moveX, moveY);
          lines[id].x = ret.x;
          lines[id].y = ret.y;
          var page = canvas.id.replace('page', '');
          xx += lines[id].x + ',' + lines[id].y + ',' + ctxt.lineWidth + ';';
        });
        event.preventDefault();
      },

      move: function(i, changeX, changeY) {
        ctxt.strokeStyle = lines[i].color;
        ctxt.beginPath();
        ctxt.moveTo(lines[i].x, lines[i].y);
        ctxt.lineTo(lines[i].x + changeX, lines[i].y + changeY);
        ctxt.stroke();
        ctxt.closePath();
        return { x: lines[i].x + changeX, y: lines[i].y + changeY };
      },
    };
    return self.init();
  },

  /***********************************************
   ******************获取http对象*******************
   ************************************************/
  gethttps: function() {
    var xmlhttp;
    if (window.XMLHttpRequest) {
      // code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp = new XMLHttpRequest();
    } else {
      // code for IE6, IE5
      xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }
    return xmlhttp;
  },

  /***********************************************
   ******************获取url变量*******************
   ************************************************/
  getUrlParam: function(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    var r = location.search.substr(1).match(reg);
    if (r !== null) {
      return unescape(r[2]);
    }
    return null;
  },

  /***********************************************
   *******************笔迹坐标获取******************
   ************************************************/
  mouseCoords: function(ev, page) {
    if (ev.offsetX || ev.offsetY) {
      return { x: ev.offsetX, y: ev.offsetY };
    }
    return {
      x: ev.layerX - document.getElementById('page' + page).offsetLeft,
      y: ev.layerY - document.getElementById('page' + page).offsetTop,
    };
  },

  /***********************************************
   ************判断浏览器是否支持html5*************
   ************************************************/

  checkobj: function() {
    try {
      var b = document.getElementById('page');
      var cxtb = b.getContext('2d');
    } catch (e) {
      document.getElementById('div_book').innerHTML = '您的浏览器还不支持html5，请更换浏览器再试';
      return false;
    }
  },

  /***********************************************
   ********************初始化对象*****************
   ************************************************/

  signatureinit: function() {
    let hit = document.getElementById('sign-page').clientHeight - 145;
    var filename = 'pge'; //getUrlParam("FileName");
    var pagenum = 1; //getUrlParam("PageNum");
    var htmlcaons = '';
    for (let i = 0; i < pagenum; i++) {
      htmlcaons +=
        "<canvas id='page" +
        i +
        "' width='1000px' height='" +
        hit +
        'px' +
        "' background='#ffffff' class='div_cans' onmouseout='onm=0;' onmousedown='onm=1;' onmouseup='mup()' onmousemove='sign(event," +
        i +
        ")'></canvas>";
    }
    document.getElementById('div_book').innerHTML = htmlcaons;
    for (var i = 0; i < pagenum; i++) {
      var cname = 'page' + i;
      var asd = new this.CanvasDrawr({ id: cname, size: 9 });
      //showtxt(i);
      this.showbook(filename, i);
    }
  },

  /***********************************************
   ***************设置预设显示内容*****************
   ************************************************/
  //
  //function showtxt(page){
  //	var b=document.getElementById("page"+page);
  //	var cxtb=b.getContext("2d");
  //	cxtb.font="60px impact";
  //	cxtb.fillStyle="#CCCCCC";
  //	cxtb.textAlign="center";
  //	cxtb.fillText('努力加载中。。。',450,500,400);
  //	cxtb.restore();
  //	cxtb.closePath();
  //}

  /***********************************************
   ***************设置显示文档内容*****************
   ************************************************/

  showbook: function(filename, page) {
    var book = new Image();
    //book.src="./img/"+filename+"_"+page+".png";
    book.onload = function() {
      var b = document.getElementById('page' + page);
      var cxtb = b.getContext('2d');
      cxtb.lineWidth = lineWidth;
      cxtb.drawImage(book, 0, 0, 500, 1000);
    };
  },

  /***********************************************
   *******************手写笔迹******************
   ************************************************/

  sign: function(ev, page) {
    ev = ev || window.event;
    var mousePos = this.mouseCoords(ev, page);
    if (onm == 1) {
      var b = document.getElementById('page' + page);
      var cxtb = b.getContext('2d');
      cxtb.strokeStyle = '#000000';
      cxtb.lineWidth = lineWidth;
      cxtb.miterLimit = 0;
      x = Math.round(mousePos.x);
      y = Math.round(mousePos.y);
      if (ones == 1) {
        cxtb.moveTo(x, y);
        if (this.beforePage == page) {
          xx += '(' + x + ',' + y + ',' + cxtb.lineWidth + ';';
        } else {
          if (xx == '') {
            xx +=
              '<' +
              page +
              ',' +
              document.getElementById('page' + page).width +
              ',' +
              document.getElementById('page' + page).height +
              ',' +
              cxtb.strokeStyle +
              '(' +
              x +
              ',' +
              y +
              ',' +
              cxtb.lineWidth +
              ';';
          } else {
            xx +=
              '><' +
              page +
              ',' +
              document.getElementById('page' + page).width +
              ',' +
              document.getElementById('page' + page).height +
              ',' +
              cxtb.strokeStyle +
              '(' +
              x +
              ',' +
              y +
              ',' +
              cxtb.lineWidth +
              ';';
          }
        }
      } else {
        xx += x + ',' + y + ',' + cxtb.lineWidth + ';';
      }
      if (this.ispad == 0) {
        cxtb.lineTo(x, y);
        cxtb.stroke();
        ones = 0;
      }
      this.beforePage = page;
    } else {
      x = 0;
      y = 0;
    }
  },

  /***********************************************
   *******************落笔结束********************
   ************************************************/

  mup: function() {
    onm = 0;
    ones = 1;
    xx += ')';
  },

  /***********************************************
   *******************保存笔迹******************
   ************************************************/

  Save: function() {
    xx = xx + ')>';
    xx = xx.replace('))', ')');
    xx = xx.replace('()', '');
    alert(xx);
    document.getElementById('biji').value = xx;
    var postStr = 'SIGN=' + xx + '&tmp=' + Math.random();
    //var oHttp=new ActiveXObject("Microsoft.XMLHTTP");
    console.log('1' + postStr);
    //console.log("2"+oHttp);

    //oHttp.open("POST","sign.php",false);
    //oHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //oHttp.send(postStr);
    //location="./end.html";
    naviDialog.hide();
  },

  //清空笔记
  Resetsign: function() {
    naviDialog.hide();
    //$scope.vehiche.popPage();//返回上一页
    //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; //android终端或者uc浏览器
    //var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    //if (isAndroid) {
    //    window.Androidhars.back();
    //} else if (isiOS) {
    //    window.location.href = 'ios://goBacklast';
    //}
  },
};
let xx = signs.pagewrite;
export { signs, xx };
